package Presentacion;

import Clases.Mail;
import Clases.Usuario;
import Control.ControlEmpleado;
import Control.ControlUsuario;
import Gestor.GestorEmpleado;
import Gestor.GestorPago;
import de.javasoft.plaf.synthetica.SyntheticaLookAndFeel;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class Ingreso extends javax.swing.JFrame {

    /**
     * Variables de la clase.
     */
    private ImageIcon check;
    private ImageIcon salir;
    private ImageIcon logo;
    private static Ingreso instancia = null;
    ControlUsuario controlU = ControlUsuario.obtenerInstancia();

    /**
     * Método que crea una sola instancia para esta clase.
     */
    public static Ingreso obtenerInstancia() {
        if (instancia == null) {
            instancia = new Ingreso();
        }
        return instancia;
    }

    /**
     * Constructor de la clase que inicializa todos sus elementos.
     */
    public Ingreso() {
        initComponents();
        check = new ImageIcon(getClass().getResource("/Imagenes/check.png"));
        salir = new ImageIcon(getClass().getResource("/Imagenes/salir.png"));
        logo = new ImageIcon(getClass().getResource("/Imagenes/logo.jpg"));
        jButton2.setIcon(check);
        jButton1.setIcon(salir);
        btnImagen.setIcon(logo);

    }

    /**
     * Método que hace visible esta interfaz con sus respectivas propiedades.
     * Asigna también un Look And Feel a la interfaz.
     */
    public void init() {
        setTitle("Ingreso");
        setLocationRelativeTo(null);
        UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
        SwingUtilities.updateComponentTreeUI(this);
        try {
            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaAluOxideLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.setVisible(true);
    }

    /**
     * Valida que los datos del usuario que ingresa sean validos
     */
    public void validarIngreso(String email, String contrasena) {
        boolean existe = controlU.ExisteUsuario(email, contrasena);
        if (existe) {
            dispose();
            Principal p = Principal.obtenerInstancia();
            Usuario u = controlU.getUsuario(email);
            p.init(u.getUsuario());
            try{
              ControlEmpleado controlEmpleado=ControlEmpleado.obtenerInstancia();
                if(!controlEmpleado.hayPagos()){
                    controlEmpleado.crearPagos();
                }
            }catch(Exception e){
                System.out.println(e.getCause());
            System.out.println(e.getMessage());
            }
                
        } else {
            JOptionPane.showMessageDialog(null, "El usuario y la contraseña no coinciden. ", "Mensaje", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Método que envíar un correo para recuperar la contraseña.
     */
    public void recuperarContrasena(String email) {
        Usuario usuario = controlU.getUsuario(email);
        String contrasena = usuario.getContrasena();
        Mail mail = new Mail();
        mail.enviar(email, "Recuperar Contraseña", "Su contraseña es: " + contrasena);
        JOptionPane.showMessageDialog(null, "Su contraseña ha sido enviada al correo.", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
        this.limpiar();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jPasswordField1 = new javax.swing.JPasswordField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        btnImagen = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Sistema de Planilla (SIPE)");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Usuario : ");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Contraseña: ");

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyPressed(evt);
            }
        });

        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Aceptar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        btnImagen.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        btnImagen.setFocusable(false);

        jCheckBox1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jCheckBox1.setText("Recuperar contraseña");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(btnImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addComponent(jLabel1))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 158, Short.MAX_VALUE)
                                    .addComponent(jPasswordField1)))
                            .addComponent(jCheckBox1))))
                .addGap(0, 81, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(btnImagen, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jCheckBox1)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.ingresar();
    }//GEN-LAST:event_jButton2ActionPerformed
    /**
     * Método que permite que el usuario ingrese al sistema, una vez validados
     * los datos se redirigue a la pantalla principal del sistema.
     */
    public void ingresar() {
        try{
        String usuario = jTextField1.getText();
        char[] contrasena1 = jPasswordField1.getPassword();
        String contrasena = new String(contrasena1);
        boolean seleccionado = jCheckBox1.isSelected();
        if (!seleccionado) {
            if (!usuario.equals("") && !contrasena.equals("")) {
                Usuario encontrado = controlU.getUsuarioNombreU(usuario.toLowerCase());
                if (encontrado != null) {
                    this.validarIngreso(encontrado.getEmail(), contrasena);
                } else {
                    JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no es válido", "Mensaje", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Campos sin completar", "Mensaje", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            if (!usuario.equals("")) {
                Usuario encontrado = controlU.getUsuarioNombreU(usuario);
                if (encontrado != null) {
                    this.recuperarContrasena(encontrado.getEmail());
                } else {
                    JOptionPane.showMessageDialog(null, "El nombre de usuario ingresado no es válido", "Mensaje", JOptionPane.ERROR_MESSAGE);

                }
            } else {
                JOptionPane.showMessageDialog(null, "Por favor ingrese el nombre de usuario para poder recuperar la contraseña", "Mensaje", JOptionPane.ERROR_MESSAGE);
            }
        }
        }
        catch(Exception e){
             JOptionPane.showMessageDialog(null, "No se ha podido establecer la conexión con el servidor", "Mensaje", JOptionPane.ERROR_MESSAGE);
        }
                }

    /**
     * Método que limpia los elementos de la interfaz.
     */
    public void limpiar() {
        jTextField1.setText("");
        jPasswordField1.setText("");
        jCheckBox1.setSelected(false);
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * Evento que reconoce la tecla Enter del teclado
     */
    private void jPasswordField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyPressed
        int key = evt.getKeyCode();
        if (key == evt.VK_ENTER) {
            this.ingresar();
        }
    }//GEN-LAST:event_jPasswordField1KeyPressed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Ingreso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        JFrame.setDefaultLookAndFeelDecorated(true);
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Ingreso().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnImagen;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
